# -*- coding: utf-8 -*-

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core import urlresolvers
from django.conf import settings
import math
from game.models import Ant, Base, MovementReport

class MovementResources(models.Model):

    CH_STATUS = (
        ('P', u'Processing'), # En viaje
        ('F', u'Finished'), # En entrega
        ('B', u'Backed'), # De vuelta
        ('FB', u'Finished Backed'), # Finalizado tras volver
        ('N', u'Null'), # Si conquistan o es destruido el hormiguero de origen
    )

    status = models.CharField(verbose_name=_(u'Status movement'), max_length=3,
                    blank=False, null=False, choices=CH_STATUS)

    base_start = models.ForeignKey('game.Base', verbose_name=_(u"Base Start"),
                    blank=False, null=False, related_name='movements_start')

    base_finish = models.ForeignKey('game.Base', verbose_name=_(u"Base Finish"),
                    blank=False, null=False, related_name='movements_finish')

    resources = models.FloatField(verbose_name=_(u'Number of resources'),
                    blank=False, null=False)

    seconds = models.PositiveIntegerField(verbose_name=_(u'Seconds'),
                    blank=True, null=True)

    success = models.BooleanField(verbose_name=_(u'Success Movement?'),
                    default=True)

    date_created = models.DateTimeField(null=False, auto_now_add=True)
    date_updated = models.DateTimeField(null=False, auto_now=True)

    class Meta:
        app_label = 'game'
        verbose_name = _(u'Movement Resources')
        verbose_name_plural = _(u'Movements Resources')

    def __unicode__(self):
        return unicode(self.id) + u' -- ' + unicode(self.get_status_display())


    def save(self, *args, **kwargs):
        if not self.pk: # Movement initialized
            super(MovementResources, self).save(*args, **kwargs)
            if self.base_start.resources < self.resources:
                raise Exception(u'No tienes suficientes recursos para el envío.')
            # Send worker ants 
            ants = self.base_start.ants_base.filter(player=self.base_start.player, type_ant = 'W', position = 'C')
            if (len(ants) * settings.WORKER_SENDING) < self.resources:
                raise Exception(u'No tienes suficientes hormigas obreras para el envío.')

            resources_aux = self.resources
            index = 0

            while(resources_aux > 0):
                ant = ants[index]
                ant.in_movement_resources = self
                ant.position = 'M'
                ant.save()
                index += 1
                resources_aux -= settings.WORKER_SENDING
            self.base_start.resources -= self.resources
            self.base_start.save()
            self.seconds = self.calculate_seconds()

        super(MovementResources, self).save(*args, **kwargs)

    # Movement finished
    def resolve_back(self):
        base_init = Base.objects.get(id = self.base_start.id)
        self.base_start = base_init
        self.base_start.save()

        ants = Ant.objects.filter(in_movement_resources = self)
        if ants.exists():
            if self.base_start.player == ants[0].player:
                ants.update(in_movement_resources=None, position='C')
                if self.success == False:
                    self.base_start.resources += self.resources
                    self.base_start.save()

        self.status= 'FB'
        self.save()

    # Movement Impact
    def resolve(self):
        base_end = Base.objects.get(id = self.base_finish.id)
        self.base_finish = base_end
        self.base_finish.save()

        if self.base_finish.player:
            self.base_finish.resources += self.resources
            self.base_finish.save()
            name_finish = self.base_finish.player.name
            info = _(u'El hormiguero' + self.base_finish.get_coordinates_string() + u' recibe '+ unicode(round(self.resources)) + u' recursos.')
        else:
            self.success = False
            name_finish = u''
            info = _(u'El hormiguero ' + 
                    self.base_finish.get_coordinates_string() + u' está ' 
                    + 'desocupado. No hay envío de recursos.')


        report = MovementReport(movement=self,
                                name_start=self.base_start.player.name,
                                name_finish=name_finish, info=info)
        report.save()

        self.status = 'B'
        self.save()



    # private
    def calculate_seconds(self):
        slow_speed = settings.SPEED[0]
        diff_x = self.base_start.x_coordinate - self.base_finish.x_coordinate
        diff_y = self.base_start.y_coordinate - self.base_finish.y_coordinate
        hypotenuse = math.sqrt(pow(diff_x, 2) + pow(diff_y, 2))

        seconds = (hypotenuse * 60) / slow_speed # 60 seconds
        bonus_seconds = 0
        if self.base_start.player.bonus == 'S': # Bonus Player
            bonus_seconds += seconds * 0.1

        if self.base_start.player.bases.filter(bonus='S').exists(): # Bonus Base
            bonus_seconds += seconds * 0.1
        seconds = round(seconds - bonus_seconds)

        return seconds

    
    """

    ESTUDIAR POR QUÉ TENEMOS QUE CONSULTAR Y GUARDAR (ACTUALIZAR) LAS BASES EN CADA PASO DE MOVIMIENTO DE RECURSOS, ATAQUES O APOYOS.

    base_end = Base.objects.get(id = self.base_finish.id)
    self.base_finish = base_end
    self.base_finish.save()
    base_init = Base.objects.get(id = self.base_start.id)
    self.base_start = base_init
    self.base_start.save()
    """


    """
    Comprobar eficiencia de las diferentes consultas, para saber cuál es más eficiente.
    # ants = Ant.objects.filter(in_movement_resources = self)
    # ants = Ant.objects.filter(type_ant = 'W', player=self.base_start.player, in_movement_resources = self)
    self.base_start.ants_base.filter(in_movement_resources = self)
    self.base_start.ants_base.filter(player=self.base_start.player, type_ant = 'W', in_movement_resources = self)
    # ants = Ant.objects.filter(player=self.base_start.player, type_ant = 'W', in_movement_resources = self)
    """

